package com.xnx3.wangmarket.plugin.api.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.xnx3.j2ee.service.SqlCacheService;
import com.xnx3.j2ee.service.SqlService;
import com.xnx3.j2ee.service.UserService;
import com.xnx3.j2ee.util.ActionLogUtil;
import com.xnx3.j2ee.util.SafetyUtil;
import com.xnx3.j2ee.vo.BaseVO;
import com.xnx3.kefu.core.entity.Kefu;
import com.xnx3.kefu.core.service.KefuService;
import com.xnx3.wangmarket.plugin.api.entity.InsetKefu;

/**
 * 坐席操作
 * @author 管雷鸣
 */
@Controller(value="ZuoxiApiPluginController")
@RequestMapping("/plugin/api/")
public class ZuoxiController extends BaseController {
	@Resource
	private SqlService sqlService;
	@Resource
	private UserService userService;
	@Resource
	private SqlCacheService sqlCacheService;
	@Resource
	private KefuService kefuService;

	/**
	 * 给客服平台中添加坐席
	 * @param password 64位字符串，也就是使用 /kefu/inset/admin/createKefu.json 创建客服接口获取到的密码串
	 * @param username 登录坐席的用户名
	 * @param password 登录坐席的密码
	 * @param nickname 坐席的昵称
	 * @return 是否创建成功
	 */
	@RequestMapping(value="createZuoxi${api.suffix}", method = RequestMethod.POST)
	@ResponseBody
	public BaseVO createKefu(HttpServletRequest request,Model model,
			@RequestParam(value = "password", required = false, defaultValue = "") String password,
			@RequestParam(value = "username", required = false , defaultValue="") String username,
			@RequestParam(value = "pwd", required = false , defaultValue="") String pwd,
			@RequestParam(value = "nickname", required = false , defaultValue="") String nickname){
		
		if(password.length() != 64){
			return error("password长度错误");
		}
		InsetKefu inset = sqlCacheService.findAloneByProperty(InsetKefu.class, "password", password);
		if(inset == null){
			return error("客服平台不存在");
		}
		
		Kefu kefu = sqlCacheService.findById(Kefu.class, inset.getKefuid());
		BaseVO vo = kefuService.createZuoxi(request, username, pwd, nickname, kefu);
		if(vo.getResult() - BaseVO.SUCCESS == 0){
			//成功。日志记录
			ActionLogUtil.insertUpdateDatabase(request, "增加坐席", "zuoxiid:"+vo.getInfo()+", username:"+SafetyUtil.xssFilter(username));
		}
		
		return vo;
	}
	
	
}
